const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { authenticateToken, requireAdmin } = require('../middleware/auth');
const crypto = require('crypto');

// 生成邀请码
function generateInviteCode(userId) {
  const timestamp = Date.now();
  const userIdStr = userId.toString();
  const combined = userIdStr + timestamp;
  const hash = crypto.createHash('md5').update(combined).digest('hex');
  
  // 取前4位数字，如果不足则补充
  let code = '';
  for (let i = 0; i < hash.length && code.length < 4; i++) {
    if (/\d/.test(hash[i])) {
      code += hash[i];
    }
  }
  
  // 如果不足4位，用时间戳补充
  while (code.length < 4) {
    const timeStr = timestamp.toString();
    for (let i = timeStr.length - 1; i >= 0 && code.length < 4; i--) {
      if (!code.includes(timeStr[i])) {
        code += timeStr[i];
      }
    }
    break;
  }
  
  return code.padStart(4, '0').slice(0, 4);
}

// 获取所有邀请记录（管理员）
router.get('/records', authenticateToken, requireAdmin, async (req, res) => {
  try {
    const { status, startDate, endDate, page = 1, limit = 10 } = req.query;
    
    let query = `
      SELECT 
        ir.*,
        inviter.username as inviter_name,
        inviter.email as inviter_email,
        inviter.avatar_url as inviter_avatar,
        invitee.username as invitee_name,
        invitee.email as invitee_email,
        invitee.avatar_url as invitee_avatar,
        o.total_amount as first_purchase_amount,
        o.created_at as first_purchase_date
      FROM invite_records ir
      LEFT JOIN users inviter ON ir.inviter_user_id = inviter.id
      LEFT JOIN users invitee ON ir.invitee_user_id = invitee.id
      LEFT JOIN orders o ON ir.first_order_id = o.id
      WHERE 1=1
    `;
    
    const params = [];
    
    if (status && status !== 'all') {
      query += ' AND ir.status = ?';
      params.push(status);
    }
    
    if (startDate) {
      query += ' AND DATE(ir.invite_date) >= ?';
      params.push(startDate);
    }
    
    if (endDate) {
      query += ' AND DATE(ir.invite_date) <= ?';
      params.push(endDate);
    }
    
    query += ' ORDER BY ir.invite_date DESC';
    
    // 分页
    const offset = (page - 1) * limit;
    query += ' LIMIT ? OFFSET ?';
    params.push(parseInt(limit), parseInt(offset));
    
    const records = await db.query(query, params);
    
    // 获取总数
    let countQuery = `
      SELECT COUNT(*) as total
      FROM invite_records ir
      WHERE 1=1
    `;
    
    const countParams = [];
    if (status && status !== 'all') {
      countQuery += ' AND ir.status = ?';
      countParams.push(status);
    }
    if (startDate) {
      countQuery += ' AND DATE(ir.invite_date) >= ?';
      countParams.push(startDate);
    }
    if (endDate) {
      countQuery += ' AND DATE(ir.invite_date) <= ?';
      countParams.push(endDate);
    }
    
    const [countResult] = await db.query(countQuery, countParams);
    
    res.json({
      success: true,
      data: records,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: countResult.total,
        totalPages: Math.ceil(countResult.total / limit)
      }
    });
  } catch (error) {
    console.error('获取邀请记录失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 获取邀请统计数据（管理员）
router.get('/stats', authenticateToken, requireAdmin, async (req, res) => {
  try {
    const stats = {};
    
    // 总邀请数
    const [totalResult] = await db.query(
      'SELECT COUNT(*) as total FROM invite_records'
    );
    stats.totalInvites = totalResult.total;
    
    // 成功邀请数
    const [successResult] = await db.query(
      'SELECT COUNT(*) as successful FROM invite_records WHERE status = "completed"'
    );
    stats.successfulInvites = successResult.successful;
    
    // 总奖励金额
    const [rewardResult] = await db.query(
      'SELECT SUM(inviter_coupon_amount + invitee_coupon_amount + bonus_coupon_amount) as totalCoupons FROM invite_records'
    );
    stats.totalCoupons = rewardResult.totalCoupons || 0;
    
    // 待发放礼券数
    const [pendingResult] = await db.query(
      'SELECT COUNT(*) as pending FROM invite_records WHERE coupon_status = "partial"'
    );
    stats.pendingCoupons = pendingResult.pending;
    
    // 活跃邀请码数
    const [activeResult] = await db.query(
      'SELECT COUNT(*) as active FROM invite_records WHERE status = "pending"'
    );
    stats.activeCodes = activeResult.active;
    
    // 今日邀请数
    const [todayResult] = await db.query(
      'SELECT COUNT(*) as today FROM invite_records WHERE DATE(invite_date) = CURDATE()'
    );
    stats.todayInvites = todayResult.today;
    
    res.json({ success: true, data: stats });
  } catch (error) {
    console.error('获取邀请统计失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 生成邀请码（用户）
router.post('/generate', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    // 检查是否已有未使用的邀请码（72小时内）
    const [existingCode] = await db.query(
      `SELECT * FROM invite_records 
       WHERE inviter_user_id = ? AND status = 'pending' 
       AND invite_date > DATE_SUB(NOW(), INTERVAL 72 HOUR)
       ORDER BY invite_date DESC LIMIT 1`,
      [userId]
    );
    
    if (existingCode) {
      return res.json({
        success: true,
        message: '使用现有邀请码',
        data: {
          inviteCode: existingCode.invite_code,
          expiresAt: new Date(existingCode.invite_date.getTime() + 72 * 60 * 60 * 1000)
        }
      });
    }
    
    // 生成新的邀请码
    let inviteCode;
    let attempts = 0;
    const maxAttempts = 10;
    
    do {
      inviteCode = generateInviteCode(userId);
      const [duplicate] = await db.query(
        'SELECT id FROM invite_records WHERE invite_code = ? AND invite_date > DATE_SUB(NOW(), INTERVAL 72 HOUR)',
        [inviteCode]
      );
      
      if (!duplicate) break;
      attempts++;
    } while (attempts < maxAttempts);
    
    if (attempts >= maxAttempts) {
      return res.status(500).json({ 
        success: false, 
        message: '生成邀请码失败，请稍后重试' 
      });
    }
    
    // 保存邀请记录
    const result = await db.query(
      `INSERT INTO invite_records 
       (inviter_user_id, invite_code, status, invite_date, inviter_coupon_amount, invitee_coupon_amount, bonus_coupon_amount, coupon_status)
       VALUES (?, ?, 'pending', NOW(), 5.00, 5.00, 2.00, 'none')`,
      [userId, inviteCode]
    );
    
    res.json({
      success: true,
      message: '邀请码生成成功',
      data: {
        id: result.insertId,
        inviteCode: inviteCode,
        expiresAt: new Date(Date.now() + 72 * 60 * 60 * 1000)
      }
    });
  } catch (error) {
    console.error('生成邀请码失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 使用邀请码注册（在用户注册时调用）
router.post('/use-code', async (req, res) => {
  try {
    const { inviteCode, newUserId } = req.body;
    
    if (!inviteCode || !newUserId) {
      return res.status(400).json({ 
        success: false, 
        message: '邀请码和用户ID为必填项' 
      });
    }
    
    // 查找有效的邀请码
    const [inviteRecord] = await db.query(
      `SELECT * FROM invite_records 
       WHERE invite_code = ? AND status = 'pending' 
       AND invite_date > DATE_SUB(NOW(), INTERVAL 72 HOUR)`,
      [inviteCode]
    );
    
    if (!inviteRecord) {
      return res.status(404).json({ 
        success: false, 
        message: '邀请码无效或已过期' 
      });
    }
    
    // 检查用户是否已经被邀请过
    const [existingInvite] = await db.query(
      'SELECT id FROM invite_records WHERE invitee_user_id = ?',
      [newUserId]
    );
    
    if (existingInvite) {
      return res.status(400).json({ 
        success: false, 
        message: '该用户已经使用过邀请码' 
      });
    }
    
    // 更新邀请记录
    await db.query(
      `UPDATE invite_records 
       SET invitee_user_id = ?, registration_date = NOW(), status = 'registered', coupon_status = 'partial'
       WHERE id = ?`,
      [newUserId, inviteRecord.id]
    );
    
    // 发放注册奖励礼券
    const couponExpiry = new Date();
    couponExpiry.setDate(couponExpiry.getDate() + 30); // 30天有效期
    
    // 给邀请人发放礼券
    await db.query(
      `INSERT INTO user_coupons 
       (user_id, coupon_type, amount, description, expires_at, status, source_type, source_id, created_at)
       VALUES (?, 'cash', ?, '邀请好友注册奖励', ?, 'active', 'invite', ?, NOW())`,
      [inviteRecord.inviter_user_id, inviteRecord.inviter_coupon_amount, couponExpiry, inviteRecord.id]
    );
    
    // 给被邀请人发放礼券
    await db.query(
      `INSERT INTO user_coupons 
       (user_id, coupon_type, amount, description, expires_at, status, source_type, source_id, created_at)
       VALUES (?, 'cash', ?, '注册奖励礼券', ?, 'active', 'invite', ?, NOW())`,
      [newUserId, inviteRecord.invitee_coupon_amount, couponExpiry, inviteRecord.id]
    );
    
    res.json({
      success: true,
      message: '邀请码使用成功，奖励已发放',
      data: {
        inviterReward: inviteRecord.inviter_coupon_amount,
        inviteeReward: inviteRecord.invitee_coupon_amount
      }
    });
  } catch (error) {
    console.error('使用邀请码失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 处理首次消费奖励（在订单完成时调用）
router.post('/first-purchase', async (req, res) => {
  try {
    const { userId, orderId, orderAmount } = req.body;
    
    if (!userId || !orderId || !orderAmount) {
      return res.status(400).json({ 
        success: false, 
        message: '用户ID、订单ID和订单金额为必填项' 
      });
    }
    
    // 查找该用户的邀请记录
    const [inviteRecord] = await db.query(
      `SELECT * FROM invite_records 
       WHERE invitee_user_id = ? AND status = 'registered' AND first_order_id IS NULL`,
      [userId]
    );
    
    if (!inviteRecord) {
      return res.json({ 
        success: true, 
        message: '该用户不是通过邀请注册或已经获得过首购奖励' 
      });
    }
    
    // 更新邀请记录
    await db.query(
      `UPDATE invite_records 
       SET first_order_id = ?, status = 'completed', coupon_status = 'issued'
       WHERE id = ?`,
      [orderId, inviteRecord.id]
    );
    
    // 给邀请人发放消费奖励礼券
    const couponExpiry = new Date();
    couponExpiry.setDate(couponExpiry.getDate() + 30); // 30天有效期
    
    await db.query(
      `INSERT INTO user_coupons 
       (user_id, coupon_type, amount, description, expires_at, status, source_type, source_id, created_at)
       VALUES (?, 'cash', ?, '好友首次消费奖励', ?, 'active', 'invite_bonus', ?, NOW())`,
      [inviteRecord.inviter_user_id, inviteRecord.bonus_coupon_amount, couponExpiry, inviteRecord.id]
    );
    
    res.json({
      success: true,
      message: '首购奖励已发放',
      data: {
        bonusReward: inviteRecord.bonus_coupon_amount
      }
    });
  } catch (error) {
    console.error('处理首购奖励失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 手动发放礼券（管理员）
router.post('/issue-coupon/:id', authenticateToken, requireAdmin, async (req, res) => {
  try {
    const { id } = req.params;
    const { inviterAmount, inviteeAmount, bonusAmount, notes } = req.body;
    
    // 获取邀请记录
    const [inviteRecord] = await db.query(
      'SELECT * FROM invite_records WHERE id = ?',
      [id]
    );
    
    if (!inviteRecord) {
      return res.status(404).json({ 
        success: false, 
        message: '邀请记录不存在' 
      });
    }
    
    // 更新邀请记录
    await db.query(
      `UPDATE invite_records 
       SET inviter_coupon_amount = ?, invitee_coupon_amount = ?, bonus_coupon_amount = ?, 
           coupon_status = 'issued', notes = ?
       WHERE id = ?`,
      [inviterAmount, inviteeAmount, bonusAmount, notes, id]
    );
    
    const couponExpiry = new Date();
    couponExpiry.setDate(couponExpiry.getDate() + 30); // 30天有效期
    
    // 发放邀请人礼券
    if (inviterAmount > 0) {
      await db.query(
        `INSERT INTO user_coupons 
         (user_id, coupon_type, amount, description, expires_at, status, source_type, source_id, created_at)
         VALUES (?, 'cash', ?, '邀请奖励礼券（管理员发放）', ?, 'active', 'invite_manual', ?, NOW())`,
        [inviteRecord.inviter_user_id, inviterAmount, couponExpiry, id]
      );
    }
    
    // 发放被邀请人礼券
    if (inviteeAmount > 0 && inviteRecord.invitee_user_id) {
      await db.query(
        `INSERT INTO user_coupons 
         (user_id, coupon_type, amount, description, expires_at, status, source_type, source_id, created_at)
         VALUES (?, 'cash', ?, '注册奖励礼券（管理员发放）', ?, 'active', 'invite_manual', ?, NOW())`,
        [inviteRecord.invitee_user_id, inviteeAmount, couponExpiry, id]
      );
    }
    
    // 发放消费奖励礼券
    if (bonusAmount > 0 && inviteRecord.first_order_id) {
      await db.query(
        `INSERT INTO user_coupons 
         (user_id, coupon_type, amount, description, expires_at, status, source_type, source_id, created_at)
         VALUES (?, 'cash', ?, '消费奖励礼券（管理员发放）', ?, 'active', 'invite_manual', ?, NOW())`,
        [inviteRecord.inviter_user_id, bonusAmount, couponExpiry, id]
      );
    }
    
    res.json({ 
      success: true, 
      message: '礼券发放成功',
      data: { 
        inviterAmount, 
        inviteeAmount, 
        bonusAmount,
        totalAmount: inviterAmount + inviteeAmount + bonusAmount
      }
    });
  } catch (error) {
    console.error('发放礼券失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 获取用户的邀请记录
router.get('/my-invites', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { page = 1, limit = 10 } = req.query;
    
    const offset = (page - 1) * limit;
    
    const invites = await db.query(
      `SELECT 
         ir.*,
         invitee.username as invitee_name,
         invitee.email as invitee_email,
         invitee.avatar_url as invitee_avatar,
         o.total_amount as first_purchase_amount,
         o.created_at as first_purchase_date
       FROM invite_records ir
       LEFT JOIN users invitee ON ir.invitee_user_id = invitee.id
       LEFT JOIN orders o ON ir.first_order_id = o.id
       WHERE ir.inviter_user_id = ?
       ORDER BY ir.invite_date DESC
       LIMIT ? OFFSET ?`,
      [userId, parseInt(limit), parseInt(offset)]
    );
    
    const [countResult] = await db.query(
      'SELECT COUNT(*) as total FROM invite_records WHERE inviter_user_id = ?',
      [userId]
    );
    
    res.json({
      success: true,
      data: invites,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: countResult.total,
        totalPages: Math.ceil(countResult.total / limit)
      }
    });
  } catch (error) {
    console.error('获取用户邀请记录失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

// 获取用户邀请统计
router.get('/my-stats', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    const stats = {};
    
    // 总邀请数
    const [totalResult] = await db.query(
      'SELECT COUNT(*) as total FROM invite_records WHERE inviter_user_id = ?',
      [userId]
    );
    stats.totalInvites = totalResult.total;
    
    // 成功邀请数
    const [successResult] = await db.query(
      'SELECT COUNT(*) as successful FROM invite_records WHERE inviter_user_id = ? AND status = "completed"',
      [userId]
    );
    stats.successfulInvites = successResult.successful;
    
    // 获得的总奖励
    const [rewardResult] = await db.query(
      'SELECT SUM(inviter_coupon_amount + bonus_coupon_amount) as totalReward FROM invite_records WHERE inviter_user_id = ?',
      [userId]
    );
    stats.totalReward = rewardResult.totalReward || 0;
    
    // 待使用的邀请码
    const [pendingResult] = await db.query(
      'SELECT COUNT(*) as pending FROM invite_records WHERE inviter_user_id = ? AND status = "pending"',
      [userId]
    );
    stats.pendingInvites = pendingResult.pending;
    
    res.json({ success: true, data: stats });
  } catch (error) {
    console.error('获取用户邀请统计失败:', error);
    res.status(500).json({ success: false, message: '服务器错误' });
  }
});

module.exports = router;